// src/store/modules/auth.js
export default {
  namespaced: true,
  state: {
    token: null,         // Token状态
    userInfo: null,      // 用户信息
    isAuthenticated: false // 认证状态
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
      state.isAuthenticated = !!token;
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo;
    },
    CLEAR_AUTH(state) {
      state.token = null;
      state.userInfo = null;
      state.isAuthenticated = false;
    }
  },
  actions: {
    // 登录时存储Token
    login({ commit }, { token, rememberMe, userInfo }) {
      commit("SET_TOKEN", token);
      if (userInfo) commit("SET_USER_INFO", userInfo);
      
      // 本地持久化存储（根据rememberMe决定存储方式）
      if (rememberMe) {
        localStorage.setItem("token", token);
      } else {
        sessionStorage.setItem("token", token);
      }
    },
    
    // 应用启动时从本地存储恢复Token
    restoreToken({ commit }) {
      const token = localStorage.getItem("token") || sessionStorage.getItem("token");
      if (token) {
        commit("SET_TOKEN", token);
        return true;
      }
      return false;
    },
    
    // 退出登录
    logout({ commit }) {
      commit("CLEAR_AUTH");
      localStorage.removeItem("token");
      sessionStorage.removeItem("token");
    }
  },
  getters: {
    getToken: state => state.token,
    getUserInfo: state => state.userInfo,
    isAuthenticated: state => state.isAuthenticated
  }
};